package com.xxrl.shop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxrl.shop.common.entity.JsonResult;
import com.xxrl.shop.common.entity.ResultCode;
import com.xxrl.shop.common.utils.PageTool;
import com.xxrl.shop.common.utils.ResultTool;
import com.xxrl.shop.common.utils.StringUtils;
import com.xxrl.shop.config.log.ControllerLog;
import com.xxrl.shop.domain.Merchant;
import com.xxrl.shop.domain.User;
import com.xxrl.shop.domain.UserInfo;
import com.xxrl.shop.service.FileService;
import com.xxrl.shop.service.UserInfoService;
import com.xxrl.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.util.Pair;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * @author mis
 */
@Api(tags = {"user"})
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final UserInfoService userInfoService;
    private final FileService fileService;

    public UserController(UserService userService, PasswordEncoder passwordEncoder, UserInfoService userInfoService, FileService fileService) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
        this.userInfoService = userInfoService;
        this.fileService = fileService;
    }

    @ApiOperation(value = "Get user information", response = Merchant.class)
    @ControllerLog
    @GetMapping("userInfo")
    public JsonResult<String> userInfo() {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        if (name != null) {
            User user = userService.getUserByName(name);
            if (user == null) {
                return ResultTool.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
            }
            JSONObject json = new JSONObject();
            json.put("name", name);
            json.put("avatar",user.getAvatar());
            json.put("isMerchant",user.getIsMerchant());
            json.put("id",user.getId());
            json.put("email",user.getEmail());
            json.put("phone",user.getPhone());
            json.put("role",user.getRole());
            return ResultTool.success(json.toString());
        } else {
            return ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        }
    }

    /**
     * 根据id 查询用户
     * @param id 用户id
     * @return 查询到的结果
     */
    @ControllerLog
    @GetMapping("find")
    public JsonResult<String> find(Long id) {
        User user = userService.getUserById(id);
        return ResultTool.success(JSON.toJSON(user).toString());
    }
    /**
     * 查询所有用户
     * @return 带有所有用户的视图
     */
    @ControllerLog
    @GetMapping("list")
    public JsonResult<String> list(@RequestParam(value="page",required=false,defaultValue="0") int page,
                                   @RequestParam(value="limit",required=false,defaultValue="10") int limit) {
        Page<User> users = userService.findAll(PageRequest.of(page, limit));
        return ResultTool.success(PageTool.pageToJson(users));
    }


    /**
     * 新建用户
     * @param user 用户
     */
    @ControllerLog
    @PostMapping("add")
    public JsonResult<String> add(User user, String username) {
        user.setName(username);
        if (userService.userExist(user)) {
            return ResultTool.fail(ResultCode.USER_ACCOUNT_ALREADY_EXIST);
        }

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        UserInfo userInfo = new UserInfo();
        user.setId(null);
        user.setAvatar("http://localhost:8080/images/res.PNG");
        user.setIsMerchant(false);
        user.setRole("user");
        userService.saveUser(user);
        userInfoService.updateUserInfoByUser(user,userInfo);
        return ResultTool.success("ok");
    }

    /**
     * 修改用户
     */
    @ControllerLog
    @PostMapping("edit")
    public JsonResult<String> edit(String phone, String email, String password, Long userId) {
        User oldUser = userService.getUserById(userId);
        if (!oldUser.getEmail().equals(email) && userService.emailInUse(email)) {
            return ResultTool.fail("邮箱重复");
        }
        if (!oldUser.getPhone().equals(phone) && userService.phoneInUse(phone)) {
            return ResultTool.fail("电话重复");
        }
        oldUser.setPhone(phone);
        oldUser.setEmail(email);
        if (!StringUtils.isEmpty(password)) {
            oldUser.setPassword(passwordEncoder.encode(password));
        }
        userService.saveUser(oldUser);
        return  ResultTool.success();
    }

    /**
     * 删除用户
     * @param userId 用户id
     * @return json结果
     */
    @ControllerLog
    @PostMapping("delete")
    public JsonResult<String> delete(@RequestParam(name = "id") Long userId) {
        userService.removeUser(userId);
        return  ResultTool.success();
    }

    /**
     * 上传并更新用户头像
     * @return 用户头像的地址
     */
    @ControllerLog
    @PostMapping("uploadAvatar")
    public JsonResult<String> uploadAvatar(@RequestParam(value = "cropperedImg")String base64Str, Long userId) {
        Pair<String, Boolean> saveBase64 = fileService.saveBase64(base64Str);
        if (saveBase64.getSecond()) {
            User user = userService.getUserById(userId);
            user.setAvatar(saveBase64.getFirst());
            userService.saveUser(user);
            return ResultTool.success(saveBase64.getFirst());
        } else {
            return ResultTool.fail(saveBase64.getFirst());
        }
    }
}
